package com.gitee.l0km.javadocreader.internal;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class TypeNames {

	/**
	 * 返回类型全名
	 * 
	 * @param type
	 */
	public static String getTypeName(Type type) {
		if (type instanceof Class) {
			return getTypeName((Class<?>) type);
		} else if (type instanceof ParameterizedType) {
			return getTypeName((ParameterizedType) type);
		} else {
			return type.toString();
		}
	}

	private static String getTypeName(Class<?> type) {
		StringBuilder dimensions = new StringBuilder();
		while (type.isArray()) {
			dimensions.append("[]");
			type = type.getComponentType();
		}
		String name = type.getName().replaceAll("\\$", "\\.");
		return new StringBuilder(name).append(dimensions).toString();
	}

	/**
	 * 返回一个泛型对象的类型字符串<br>
	 * 如: {@code java.util.Map<java.lang.String,net.gdface.sdk.CodeInfo[]>}
	 * 
	 * @param type
	 */
	private static String getTypeName(ParameterizedType type) {
		StringBuilder sb = new StringBuilder();
		sb.append(getTypeName(type.getRawType()));
		Type[] actualTypeArguments = type.getActualTypeArguments();
		if (actualTypeArguments != null && actualTypeArguments.length > 0) {
			sb.append("<");
			boolean first = true;
			for (Type t : actualTypeArguments) {
				if (!first) {
					sb.append(", ");
				}
				sb.append(getTypeName(t));
				first = false;
			}
			sb.append(">");
		}
		return sb.toString();
	}

}